<?php
/**
 * This class offers basic functions to check if an SQL injection attempt has been done
 */
class SQLInjectionTester{
	
	/**
	 * check if the string contains a comment
	 * @param String $query the string to check
	 * @return bool true if the provided string is ok
	 */
	public static function checkStatement($query){
		if (SQLInjectionTester::check($query)){
			return SQLInjectionTester::check4Identical($query);
		} else {
			return false;
		}
	}
	
	/**
	 * check if the entered string (part of an SQL statement) is a comment
	 * or contains a semicolon
	 * @param String $input the string to check
	 * @return bool true if the provided string is ok
	 */
	public static function checkInput($input){
		if (SQLInjectionTester::check($input)){
			return SQLInjectionTester::check4Identical($input);
		} else {
			return false;
		}
				}
	
	/**
	 * check if part of the string is a comment or contains a semicolon
	 * @param String $string string to check
	 * @return bool true if the string is ok
	 */
	private static function check($string){
		if (strpos($string, "--")){
			return false;
		}
		if (strpos($string, "/*")){
			return false;
		}
		if (strpos($string, ";")){
			return false;
		}
		return true;
	}
	
	/**
	 * make sure no SQL statement like "id=id" is allowed
	 * @param String $input string to check
	 * @return bool true if the string is ok
	 * 	 */
	private static function check4Identical($input){
		$parts2 = explode(" ", $input);
		$parts = array();
		for($i=count($parts2)-1;$i>=0;$i--){
			if (!strlen(trim($parts2[$i]))==0){
				array_push($parts,$parts2[$i]);
			}
		}
		for($i=1;$i<count($parts)-1;$i++){
			if (strpos($parts[$i],"=")!==false && strlen($parts[$i])==1){
				// Vergleiche Teil vor '=' mit Teil nach dem '='
				$befor =$parts[$i-1];
				$after = $parts[$i+1];
				$befor = str_replace("`","",$befor);
				$befor = str_replace("'","",$befor);
				$after = str_replace("`","",$after);
				$after = str_replace("'","",$after);
				if ($befor==$after){
					return false;
				}
			}
		}
		return true;
	}
}
?>